import styles from "./index.module.less"
import Chart from "chart.js/auto"
import { make, makeModal } from "../../utils/dom"
import Handsontable from "handsontable"
import "handsontable/dist/handsontable.full.min.css"

const chartTypes = ["bar", "line", "pie"]

class ChartBox {
	static get toolbox() {
		return {
			title: "Chart",
			icon: `<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M17.2929 2.29289C17 2.58579 17 3.05719 17 4V17C17 17.9428 17 18.4142 17.2929 18.7071C17.5858 19 18.0572 19 19 19C19.9428 19 20.4142 19 20.7071 18.7071C21 18.4142 21 17.9428 21 17V4C21 3.05719 21 2.58579 20.7071 2.29289C20.4142 2 19.9428 2 19 2C18.0572 2 17.5858 2 17.2929 2.29289Z" fill="#1C274C"/>
        <path d="M10 7C10 6.05719 10 5.58579 10.2929 5.29289C10.5858 5 11.0572 5 12 5C12.9428 5 13.4142 5 13.7071 5.29289C14 5.58579 14 6.05719 14 7V17C14 17.9428 14 18.4142 13.7071 18.7071C13.4142 19 12.9428 19 12 19C11.0572 19 10.5858 19 10.2929 18.7071C10 18.4142 10 17.9428 10 17V7Z" fill="#1C274C"/>
        <path d="M3.29289 9.29289C3 9.58579 3 10.0572 3 11V17C3 17.9428 3 18.4142 3.29289 18.7071C3.58579 19 4.05719 19 5 19C5.94281 19 6.41421 19 6.70711 18.7071C7 18.4142 7 17.9428 7 17V11C7 10.0572 7 9.58579 6.70711 9.29289C6.41421 9 5.94281 9 5 9C4.05719 9 3.58579 9 3.29289 9.29289Z" fill="#1C274C"/>
        <path d="M3 21.25C2.58579 21.25 2.25 21.5858 2.25 22C2.25 22.4142 2.58579 22.75 3 22.75H21C21.4142 22.75 21.75 22.4142 21.75 22C21.75 21.5858 21.4142 21.25 21 21.25H3Z" fill="#1C274C"/>
        </svg>`,
		}
	}

	static get isReadOnlySupported() {
		return true
	}

	constructor({ data, api, config, readOnly }) {
		this.data = {
			type: data.type || "bar",
			labels: data.labels || ["周一", "周二", "周三", "周四"],
			datasets: data.datasets || [
				{
					label: "数量",
					data: [12, 19, 3, 5],
					backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)"],
					borderColor: ["rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)"],
					borderWidth: 1,
				},
			],
		}

		this.readOnly = readOnly
		this.api = api

		this.config = config || {}

		this.modalId = "cx_" + Date.now()
		this.table = null

		this.wrapper = undefined
	}

	render() {
		this.wrapper = document.createElement("div")
		this.wrapper.classList.add(styles["cx-custom-chart"])
		if (this.data) {
			const ctx = make("canvas", styles.chart)

			let myChart = new Chart(ctx, { type: this.data.type, data: this.data })

			let editBtn
			if (!this.readOnly) {
				editBtn = make("span", styles.editBtn, { innerHTML: "编辑" })
				editBtn.addEventListener(
					"click",
					() => {
						modal.style.display = "block"
					},
					false
				)
			}
			const toggleBtn = make("span", styles.toggleBtn, { innerHTML: "切换图表类型" })
			const modal = makeModal(this.modalId, false, () => {
				const allData = this.table.getData()
				const usedData = allData.filter((v) => !!v[0])
				let labels = [],
					data = [],
					bgc = [],
					label = ""
				usedData.forEach((v) => {
					labels.push(v[0])
					data.push(v[1])
					bgc.push(v[2])
					if (v[3]) {
						label = v[3]
					}
				})

				this.data = {
					type: this.data.type,
					labels,
					datasets: [
						{
							data,
							backgroundColor: bgc,
							label,
							borderColor: bgc,
							borderWidth: 1,
						},
					],
				}

				// 更新图表
				myChart.destroy()

				myChart = new Chart(ctx, { type: this.data.type, data: this.data })
			})

			this.wrapper.append(ctx, this.readOnly ? "" : editBtn, toggleBtn)

			document.body.append(modal)

			if (!this.readOnly) {
				// 渲染弹窗表格
				setTimeout(() => {
					const table = document.querySelector(`#${this.modalId}`)
					const labels = this.data.labels
					const bgColor = this.data.datasets[0].backgroundColor
					const itemValues = this.data.datasets[0].data
					const data = labels.map((v, i) => {
						return [v, itemValues[i], bgColor[i], i == 0 ? "周访问数据报表" : ""]
					})
					// 填充空数据
					if (data.length < 15) {
						data.push(...new Array(15 - data.length).fill(null).map(() => []))
					}
					this.table = new Handsontable(table, {
						data,
						colHeaders: ["数据名称", "数值", "颜色", "表格标题"],
						rowHeaders: true,
						// width: '100%',
						height: "460px",
						colWidths: (window.innerWidth * 0.6 - 52) / 4,
						autoWrapRow: true,
						autoWrapCol: true,
						licenseKey: "non-commercial-and-evaluation",
					})
				}, 800)
			}

			toggleBtn.addEventListener(
				"click",
				() => {
					const curIdx = chartTypes.findIndex((v) => v === this.data.type)
					const nextIdx = curIdx < chartTypes.length - 1 ? curIdx + 1 : 0
					this.data.type = myChart.type = chartTypes[nextIdx]

					myChart.destroy()

					myChart = new Chart(ctx, { type: this.data.type, data: this.data })
				},
				false
			)
		}

		return this.wrapper
	}

	save(blockContent) {
		return { ...this.data }
	}
}

export default ChartBox

